"use client";

import React from "react";
import { useEffect, useRef } from "react";
import { useRouter, usePathname } from "next/navigation";
import { gsap } from "gsap";
import "./index.css";
import Loading from "../Loading";

const PageTransition = ({ children }: { children: React.ReactNode }) => {
  const router = useRouter();
  const pathname = usePathname();
  const firstLayerRef = useRef<HTMLDivElement>(null);
  const secondLayerRef = useRef<HTMLDivElement>(null);
  const logoOverlayRef = useRef(null);
  const isTransitioning = useRef(false);
  const revealPagingAntimation = useRef<gsap.core.Timeline>(null);

  useEffect(() => {
    // 页面加载时执行消失动画
    revealPage();

    const handleRouteChange = (url: string) => {
      if (isTransitioning.current) return;
      isTransitioning.current = true;
      coverPage(url);
    };

    const links = document.querySelectorAll("a");
    const linkEvent = (e: any) => {
      e.preventDefault();
      const href = e.currentTarget.href;
      const url = new URL(href).pathname;
      if (url !== pathname) {
        handleRouteChange(url);
      }
    };
    links.forEach((link) => {
      link.addEventListener("click", linkEvent);
    });

    return () => {
      links.forEach((link) => {
        link.removeEventListener("click", linkEvent);
      });
    };
  }, [router, pathname]);

  const coverPage = (url: string) => {
    const links = document.querySelectorAll("a");
    links.forEach((link) => {
      link.style.pointerEvents = "none";
    });
    const tl = gsap.timeline({
      onComplete: () => router.push(url),
    });

    // 先将两层重置到屏幕下方
    tl.set([firstLayerRef.current, secondLayerRef.current], { y: "100%" })
      // 第一层从下往上移动
      .to(firstLayerRef.current, {
        y: "-2%", // 稍微超出一点，确保圆角完全覆盖
        duration: 0.8,
        ease: "power2.out",
      })
      // 第二层稍微延迟一点，也从下往上移动
      .to(
        secondLayerRef.current,
        {
          y: "-2%", // 稍微超出一点，确保圆角完全覆盖
          duration: 0.7,
          ease: "power2.out",
        },
        "-=0.4"
      ) // 提前0.4秒开始，创造重叠效果
      // 显示loading
      .set(logoOverlayRef.current, { opacity: 1 }, "-=0.1");
  };

  const revealPage = () => {
    // 页面显示时，两层都从上往下退回去
    const tl = gsap.timeline({
      onComplete: () => {
        isTransitioning.current = false;
        const links = document.querySelectorAll("a");
        links.forEach((link) => {
          link.style.pointerEvents = "auto";
        });
      },
    });
    revealPagingAntimation.current = tl;

    tl.to(
      // loading淡出
      logoOverlayRef.current,
      {
        opacity: 0,
        duration: 0.3,
        ease: "power2.out",
      },
      "+=0.2"
    ); // 等待0.2秒后开始淡出

    // 第二层先退回（从上往下）
    tl.to(secondLayerRef.current, {
      y: "100%",
      duration: 0.6,
      ease: "power2.out",
    })
      // 第一层稍微延迟一点退回
      .to(
        firstLayerRef.current,
        {
          y: "100%",
          duration: 0.6,
          ease: "power2.out",
        },
        "-=0.3"
      ); // 提前0.3秒开始，创造重叠效果
  };

  useEffect(() => {
    // 第一次进来的话 可以给一个loading
    const setLoading = (e: Event | boolean) => {
      if (revealPagingAntimation.current && e)
        revealPagingAntimation.current.kill();
      // 初始化两层的位置 - 都在屏幕上方（覆盖整个屏幕）
      gsap.set([firstLayerRef.current, secondLayerRef.current], {
        y: "0%",
      });
      gsap.set(logoOverlayRef.current, { opacity: 1 });
    };

    setLoading(false);
    window.addEventListener("popstate", setLoading);
    return () => {
      window.removeEventListener("popstate", setLoading);
    };
  }, []);
  return (
    <>
      {/* 第一层 - 稍微深一点的颜色 */}
      <div
        ref={firstLayerRef}
        className="fixed top-0 left-0 w-screen h-[105vh] pointer-events-none z-[998] bg-blue-200 rounded-t-3xl"
      />

      {/* 第二层 - 浅一点的颜色，包含loading */}
      <div
        ref={secondLayerRef}
        className="fixed top-0 left-0 w-screen h-[105vh] pointer-events-none z-[999] bg-blue-100 rounded-t-3xl"
      />

      {/* Loading层 */}
      <div
        ref={logoOverlayRef}
        className="fixed top-0 left-0 w-screen h-screen z-[1000] flex justify-center items-center pointer-events-none"
      >
        <div className="w-[200px] h-[200px] flex justify-center items-center p-[20px]">
          <Loading visible />
        </div>
      </div>

      {children}
    </>
  );
};

export default PageTransition;
